import http from './httpRequest'
import dayjs from 'dayjs'

/**
 * 网络请求
 * @param url
 * @param method
 * @param data
 * @param type
 * @param showLoading
 * @return {*}
 */
export function doHttp({ url, method = 'post', data, type, showLoading = true, showMessage = true }) {
  let obj = {
    url: http.adornUrl(url),
    method,
    showLoading,
    showMessage
  }

  if (method.toLocaleUpperCase() === 'GET') {
    obj.params = http.adornParams(data)
  } else if (method.toLocaleUpperCase() === 'POST' || method.toLocaleUpperCase() === 'PUT') {
    obj.data = http.adornData(data, type)
  }

  return http(obj)
}

export function getFileBlob(url, params) {
  return http.getFileBlob(http.adornUrl(url), params)
}

/**
 * 格式化日期
 * @param date
 * @param fmt
 * @return {*}
 */
export function formatDate(date, fmt = 'YYYY-MM-DD HH:mm:ss') {
  if (!date) {
    return ''
  }
  if (typeof date === 'string') {
    date = new Date(date.replace(/-/g, '/'))
  }
  if (typeof date === 'number') {
    date = new Date(date)
  }
  let o = {
    'M+': date.getMonth() + 1,
    'D+': date.getDate(),
    'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
    'H+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    S: date.getMilliseconds()
  }
  let week = {
    0: '\u65e5',
    1: '\u4e00',
    2: '\u4e8c',
    3: '\u4e09',
    4: '\u56db',
    5: '\u4e94',
    6: '\u516d'
  }
  if (/(Y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  if (/(E+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length > 1 ? (RegExp.$1.length > 2 ? '\u661f\u671f' : '\u5468') : '') + week[date.getDay() + ''])
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
    }
  }
  return fmt
}

/**
 * 根据日期获取当月的天数
 * @param date 日期，默认当前日期
 * @param offset 距离当月的月份，默认0
 * @returns {{month: number, year: number, days: number}}
 */
export function getDaysOfMonth(date = new Date(), offset = 0) {
  let fullYear = date.getFullYear()
  let month = date.getMonth() + 1

  // 如果月份有偏移
  if (offset !== 0) {
    month = month + offset
    // 如果偏移到去年或者更久远
    if (month <= 0) {
      month = (month % 12) + 12
      fullYear = fullYear - (Math.ceil(Math.abs(-24) / 12) + 1)
    } else if (month > 12) {
      month = month % 12 === 0 ? 12 : month % 12
      fullYear = fullYear + Math.floor((month - 1) / 12)
    }
  }

  return {
    year: fullYear,
    month,
    days: new Date(fullYear, month, 0).getDate()
  }
}

/**
 * 获取周名称
 * @param week
 * @param isSundayFirst
 */
export function getWeekName(week, isSundayFirst = true) {
  let weekName = ''
  let weekSimpleName = ''
  if (!isSundayFirst) {
    week = (week + 1) % 7
  }
  switch (week) {
    case 0:
      weekName = '周日'
      weekSimpleName = '日'
      break
    case 1:
      weekName = '周一'
      weekSimpleName = '一'
      break
    case 2:
      weekName = '周二'
      weekSimpleName = '二'
      break
    case 3:
      weekName = '周三'
      weekSimpleName = '三'
      break
    case 4:
      weekName = '周四'
      weekSimpleName = '四'
      break
    case 5:
      weekName = '周五'
      weekSimpleName = '五'
      break
    case 6:
      weekName = '周六'
      weekSimpleName = '六'
      break
  }

  return {
    weekName,
    weekSimpleName
  }
}

/**
 * 判断对象是否为空
 * @param obj
 * @return {boolean}
 */
export function isObjectEmpty(obj) {
  let arr = Object.keys(obj)
  if (arr.length === 0) {
    return true
  }
  return false
}

export function getOS() {
  let nAgt = navigator.userAgent
  let os = 'None'
  let clientStrings = [
    {
      s: 'Windows Phone',
      r: /Windows Phone/
    },
    {
      s: 'Android',
      r: /Android/
    },
    {
      s: 'iOS',
      r: /(iPhone|iPad|iPod)/
    }
  ]
  for (let i = 0, len = clientStrings.length; i < len; i++) {
    let cs = clientStrings[i]
    if (cs.r.test(nAgt)) {
      os = cs.s
      break
    }
  }

  return os
}

export function getBrowser() {
  let ua = navigator.userAgent
  let brower
  let rules = [
    {
      name: 'QQ mobile',
      rule: /MQQBrowser\/(\d+\.\d+)/
    },
    {
      name: 'QQ',
      rule: /QQBrowser\/(\d+\.\d+)/
    },
    {
      name: 'Chrome Mobile',
      rule: /(?:Android.*Chrome|.*CriOS)\/(\d+)/
    },
    {
      name: 'Android Webkit Browser',
      rule: /Android.*Version\/(\d+\.\d+).*Mobile/
    },
    {
      name: 'Chrome',
      rule: /Chrome\/(\d+)/
    },
    {
      name: 'Safari Mobile',
      rule: /(?:iPhone|iPad).*Mobile/
    },
    {
      name: 'Safari',
      rule: /Version\/(\d+\.\d+).*Safari/
    }
  ]

  for (let i = 0, len = rules.length; i < len; i++) {
    let res = rules[i].rule.exec(ua)
    if (res) {
      brower = rules[i].name
      break
    }
  }

  return brower || 'Other'
}

export function parseQueryString(str, sep, eq) {
  if (typeof str === 'undefined' && typeof document !== 'undefined') {
    str = document.location.search
  }
  let ret = {}

  if (typeof str !== 'string' || trim(str).length === 0) {
    return ret
  }

  // remove ^?
  str = str.replace(/^\?/, '')

  let pairs = str.split(sep || '&')
  eq = eq || '='

  for (var i = 0; i < pairs.length; i++) {
    let pair = pairs[i].split(eq)
    let key = unescape(trim(pair[0]))
    let val = unescape(trim(pair.slice(1).join(eq)))

    let m = key.match(/^(\w+)\[\]$/)
    if (m && m[1]) {
      key = m[1]
    }

    if (hasOwnProperty.call(ret, key)) {
      if (!isArray(ret[key])) {
        ret[key] = [ret[key]]
      }
      ret[key].push(val)
    } else {
      ret[key] = m ? [val] : val
    }
  }

  return ret
}

const toString = Object.prototype.toString
const hasOwnProperty = Object.prototype.hasOwnProperty
export const isArray =
  Array.isArray ||
  function (val) {
    return toString.call(val) === '[object Array]'
  }
export const trim = String.prototype.trim
  ? function (str) {
      return str == null ? '' : String.prototype.trim.call(str)
    }
  : function (str) {
      return str == null ? '' : str.toString().replace(/^\s+/, '').replace(/\s+$/, '')
    }

/**
 * 随机生成UUID
 * @returns {String} C277116A-EF96-4D91-91E5-F4AD5470B6A5
 */
export const UUIDFast = () => {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  const uuid = new Array(36)
  let rnd = 0
  let r
  for (let i = 0; i < 36; i++) {
    if (i === 8 || i === 13 || i === 18 || i === 23) {
      uuid[i] = '-'
    } else if (i === 14) {
      uuid[i] = '4'
    } else {
      if (rnd <= 0x02) rnd = (0x2000000 + Math.random() * 0x1000000) | 0
      r = rnd & 0xf
      rnd = rnd >> 4
      uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r]
    }
  }
  return uuid.join('')
}

export const getSuffixByUrl = (filename) => {
  let pos = filename.lastIndexOf('.')
  let suffix = ''
  if (pos !== -1) {
    suffix = filename.substring(pos)
  }
  return suffix
}

export const getFilename = (filename) => {
  let pos = filename.lastIndexOf('.')
  let name = ''
  if (pos != -1) {
    name = filename.substring(0, pos)
  }
  return name
}

export const isImageUrl = (url) => {
  if (!url) {
    return false
  }
  const reg = /\.(png|jpe?g|gif|svg)(\?.*)?$/
  return reg.test(url)
}

export const formatNumber = (num, precision = 2) => {
  if (!num) return '-'
  if (isNaN(num)) return num
  const reg = /(-?\d+)(\d{3})/
  num = Number(num).toFixed(precision).toString()
  while (reg.test(num)) {
    num = num.replace(reg, '$1,$2')
  }
  return num
}

/**
 * 深拷贝
 * @param target
 * @returns {{}}
 */
export function deepClone(target) {
  // 定义一个变量
  let result
  // 如果当前需要深拷贝的是一个对象的话
  if (typeof target === 'object') {
    // 如果是一个数组的话
    if (Array.isArray(target)) {
      result = [] // 将result赋值为一个数组，并且执行遍历
      for (let i in target) {
        // 递归克隆数组中的每一项
        result.push(deepClone(target[i]))
      }
      // 判断如果当前的值是null的话；直接赋值为null
    } else if (target === null) {
      result = null
      // 判断如果当前的值是一个RegExp对象的话，直接赋值
    } else if (target.constructor === RegExp) {
      result = target
    } else {
      // 否则是普通对象，直接for in循环，递归赋值对象的所有值
      result = {}
      for (let i in target) {
        result[i] = deepClone(target[i])
      }
    }
    // 如果不是对象的话，就是基本数据类型，那么直接赋值
  } else {
    result = target
  }
  // 返回最终结果
  return result
}

/**
 * 获取产品浮动盈亏曲线图参数
 * @returns
 */
export const getProfitLossReportParam = (activeChartTimeType) => {
  const today = dayjs().format('YYYY-MM-DD')
  const param = {
    endDate: today
  }
  switch (activeChartTimeType) {
    case 0:
      param.startDate = dayjs(today).subtract(6, 'month').format('YYYY-MM-DD')
      break
    case 1:
      param.startDate = dayjs().startOf('year').format('YYYY-MM-DD')
      break
    case 2:
      // param.startDate = dayjs(today).subtract(12, 'month').format('YYYY-MM-DD')
      break
    default:
      break
  }
  return param
}

/**
 * 根据数值大小格式化金额显示，超过一亿，显示xx亿，超过一万，显示xx万
 * @param {*} num
 * @param {*} precision
 * @returns
 */
export const formatAmountBySize = (num, precision = 2) => {
  if (num === null || num === undefined || isNaN(num)) {
    return '-'
  }
  num = Number(num)
  if (Math.abs(num) >= 100000000) {
    return (num / 100000000).toFixed(precision)
  } else if (Math.abs(num) >= 10000) {
    return (num / 10000).toFixed(precision)
  } else {
    return num.toFixed(precision)
  }
}

/**
 * 根据数值大小格式化金额显示，超过一亿，显示亿，超过一万，显示万
 */
export const formatAmountTextBySize = (num) => {
  if (num === null || num === undefined || isNaN(num)) {
    return '万'
  }
  num = Number(num)
  if (Math.abs(num) >= 100000000) {
    return '亿'
  } else if (Math.abs(num) >= 10000) {
    return '万'
  } else {
    return '元'
  }
}
